import type { MouseEvent } from 'react';
import type { TocItem } from 'md-editor-rt/lib/types/MdCatalog';
import { MdCatalog, MdEditor } from 'md-editor-rt';
import { useModel } from '@umijs/max';
import { debounce } from '@/utils';
import styles from './index.less';

const scrollElement = document.documentElement;
interface PropsType {
  content: string;
}

const ReadExtension: React.FC<PropsType> = (props) => {
  const { markDownStore } = useModel('markDown');
  const generateId = (_text: string, _level: number, index: number): string => `heading-${index}`;
  const onHtmlChanged = debounce(() => {
    const { hash } = location;
    if (/^#/.test(hash)) {
      const headingId = decodeURIComponent(hash.replace('#', ''));

      if (headingId) {
        const targetHeadDom = document.getElementById(headingId);

        if (targetHeadDom) {
          const scrollLength = (targetHeadDom as HTMLHeadElement).offsetTop;
          window.scrollTo({
            top: scrollLength,
            behavior: 'smooth',
          });
        }
      }
    }
  });

  const onClick = (e: MouseEvent, t: TocItem) => {
    history.replaceState({}, '', `${location.pathname}#${t.text}`);
  };

  return (
    <div className={styles.mdViewWrapper}>
      <MdEditor
        className={styles.mdEditorWrapper}
        theme={markDownStore.theme}
        language={markDownStore.lang}
        previewTheme={markDownStore.previewTheme}
        codeTheme={markDownStore.codeTheme}
        editorId="md-editor-preview"
        showCodeRowNumber
        onHtmlChanged={onHtmlChanged}
        modelValue={props.content}
      />
      <div className={styles.mdCatalogWrapper}>
        <MdCatalog
          theme={markDownStore.theme}
          editorId="md-editor-preview"
          scrollElement={scrollElement}
          mdHeadingId={generateId}
          onClick={onClick}
        />
      </div>
    </div>
  );
};

export default ReadExtension;
